<template>
    <div style="height: 6vh;background-color:#fff;padding: 10px 20px;">
    <span style="line-height:60px;font-size:20px;">用户管理</span>
    <el-button type="primary" style="float: right;margin-top: 10px;"
    @click="beforeAddUser">新建用户</el-button>
  </div>
  <!-- 新建用户弹窗 -->
  <!-- :before-close="handleClose" 在弹窗关闭前先调用handleClose方法来处理弹窗的关闭问题
   避免点击弹窗外部也能关闭弹窗-->
  <el-dialog
    :title="dialogTitle"
    style="width: 1000px;padding: 40px;"
    v-model="dialogVisible"
    :before-close="handleClose"
  >
    <el-form label-position="top" label-width="80px" :rules="rules">
     <el-row :gutter="10">
       <el-col :span="8">
         <el-form-item label="用户名">
           <el-input placeholder="请输入用户名" v-model="saveUserForm.username"
           :disabled="saveUserForm.id != null"></el-input>
         </el-form-item>
       </el-col>
       <el-col :span="8">
         <el-form-item label="身份证号" prop="num">
           <el-input placeholder="请输入身份证号" v-model="saveUserForm.num"></el-input>
         </el-form-item>
       </el-col>
       <el-col :span="8">
         <el-form-item label="健康状态">
           <el-select placeholder="请选择" v-model="saveUserForm.status">
             <el-option v-for="item in statusOptions"
                        :label="item.label" :value="item.value"></el-option>
           </el-select>
         </el-form-item>
       </el-col>
     </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="监护人">
            <el-input placeholder="请输入监护人姓名" v-model="saveUserForm.guardianName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="监护人手机号" prop="guardianPhone">
            <el-input placeholder="请输入监护人手机号" v-model="saveUserForm.guardianPhone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="对应职工">
            <el-select placeholder="请选择职工" v-model="saveUserForm.empName">
              <el-option v-for="item in empOptions"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="生日">
            <el-date-picker type="date" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" v-model="saveUserForm.birth"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标签">
            <el-select placeholder="请选择" v-model="saveUserForm.tag">
              <el-option v-for="item in tagOptions"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="性别">
            <el-radio-group v-model="saveUserForm.gender">
              <el-radio border label="男" value="1" style="margin:0;"></el-radio>
              <el-radio border label="女" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注">
            <el-input placeholder="备注" v-model="saveUserForm.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="开户组织">
            <el-select placeholder="请选择" v-model="saveUserForm.organization">
              <el-option v-for="item in organizationOptions"
                         :label="item.label" :value="item.value"
                         :disabled="saveUserForm.id != null"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveUser">保存</el-button>
    </template>
  </el-dialog>

  <!-- 用户搜索卡片 -->
  <el-card style="margin: 20px;height: 120px;">
    <el-form :inline="true">
      <el-form-item label="用户搜索" style="width: 220px;">
        <el-input placeholder="输入用户名" v-model="searchUserForm.username" @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item label="用户性别" style="width: 220px;">
        <el-select placeholder="请选择用户性别" v-model="searchUserForm.gender" @change="loadUser">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" style="width: 220px;">
        <el-input placeholder="输入身份证号" v-model="searchUserForm.num" @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item label="健康状态" style="width: 220px;">
        <el-select placeholder="请选择用户状态" v-model="searchUserForm.status" @change="loadUser">
          <el-option v-for="item in statusOptions"
                     :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form :inline="true">
      <el-form-item label="标签" style="width: 220px;">
        <el-select placeholder="请选择用户标签" v-model="searchUserForm.tag" @change="loadUser">
          <el-option v-for="item in tagOptions"
                     :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" style="width: 220px;">
        <el-input placeholder="请输入备注" v-model="searchUserForm.remark" @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户表格卡片 -->
  <el-card style="margin: 20px;">
    <el-table :data="userArr">
      <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="username" label="老人姓名" align="center"></el-table-column>
      <el-table-column prop="guardianName" label="监护人" align="center"></el-table-column>
      <el-table-column prop="guardianPhone" label="监护人手机号" align="center"></el-table-column>
      <el-table-column prop="tag" label="标签" align="center"
                       :formatter="userTagFormatter"></el-table-column>
      <el-table-column prop="num" label="身份证号" align="center"></el-table-column>
      <el-table-column prop="empName" label="对应职工" align="center"></el-table-column>
      <el-table-column prop="age" label="年龄" align="center" ></el-table-column>
      <el-table-column prop="status" label="健康状态" align="center"
                       :formatter="userStatusFormatter"></el-table-column>
      <el-table-column prop="createTime" label="登记时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="editUser(scope.row.id)" >编辑</el-button>
          <el-button link type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
  //定义变量控制弹窗是否出现
  const dialogVisible=ref(false);
  //定义变量用来控制弹窗的标题
  const dialogTitle=ref('添加用户');
  const saveUserForm=ref({
    username:'',
    guardianPhone:'',
    age:'',
    num:'',
    tag:'',
    birth:'',
    guardianName:'',
    gender:'',
    status:'',
    remark:'',
    empName:''
  })
  const tagOptions=ref([
    {label:'高血压', value:'1'},
    {label:'糖尿病', value:'2'},
    {label:'心脏病', value:'3'},
    {label:'低血糖', value:'4'}
  ])

  const statusOptions=ref([
    {label:'健康', value:'1'},
      {label:'良好', value:'2'},
      {label:'疾病', value:'3'}
  ])
  const empOptions=ref([
    {label:'zhang', value:'101'},
    {label:'li', value:'102'},
    {label:'wang', value:'103'}
  ])
  const organizationOptions=ref([
    {label:'养老院A',value:'1'},
    {label:'养老院B',value:'2'},
    {label:'养老院C',value:'3'},
  ])
  const searchUserForm=ref({
    username:'',
    gender:'',
    num:'',
    tag:'',
    status:'',
    remark:'',
  })
  const userTagArr=ref([]);
  const userStatusArr=ref([]);
  onMounted(()=>{
    loadDictOption(userTagArr,'user_tag');
    loadDictOption(userStatusArr,'user_status');
  })
  const userTagFormatter = (row,column,cellValue,index)=>{
    if(!userTagArr.value){
      return cellValue;
    }
    for(let item of userTagArr.value){
      if(item.value==cellValue){
        cellValue = item.label;
      }
    }
    return cellValue;
  }

  const userStatusFormatter = (row,column,cellValue,index)=>{
    if(!userStatusArr.value){
      return cellValue;
    }
    for (let item of userStatusArr.value){
      if(item.value==cellValue){
        cellValue=item.label;
      }
    }
    return cellValue;
  }
  const userArr=ref([]);
  /* 点击"新建用户"按钮,出弹窗+修改弹窗标题 */
  const beforeAddUser = ()=>{
    dialogVisible.value = true;
    dialogTitle.value = '添加用户';
  }
  //定义加载用户的方法
  const loadUser=()=>{
    let data=qs.stringify(searchUserForm.value);
    axios.get(BASE_URL+'/v1/user/select?'+data).then((response)=>{
      if (response.data.code==2000){
        userArr.value=response.data.data;
        console.log(userArr);
      }else{
        ElMessage(response.data.msg);
      }
        })
  }
  onMounted(()=>{
    loadUser();
  })
  //定义重置搜索条件的方法
  const resetSearch = ()=>{
    //清空之前的搜索条件
    searchUserForm.value = {};
    //重新加载所有的用户数据
    loadUser();
  }
  const empLabelMap = {
    '101': 'zhang',
    '102': 'li',
    '103': 'wang'
  };
  //定义保存用户和监护人的方法
  const saveUser = ()=>{
    const empLabel = empLabelMap[saveUserForm.value.empName];
    if (empLabel) {
      saveUserForm.value.empName = empLabel;
    }
      let data=qs.stringify(saveUserForm.value);
    axios.post(BASE_URL+'/v1/user/save',data).then(response=>{
      if(response.data.code == 2000){
        ElMessage.success('保存成功!');
        //保存成功后关闭弹窗
        dialogVisible.value=false;
        //保存成功后清空表单数据
        saveUserForm.value={};
        //保存成功后重新加载用户数据
        loadUser();
      }
      else {
        ElMessage.error(response.data.msg);
      }
    })
  }
  const rules = ref({
    num: [
      { required: true, message: '请输入身份证号', trigger: 'blur' },
      { pattern: /^\d{18}$/, message: '身份证号必须是18位数字', trigger: 'blur' }
    ],
    guardianPhone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^\d{11}$/, message: '手机号必须是11位数字', trigger: 'blur' }
    ]
  });

  //处理弹窗关闭的方法
  const handleClose = ()=>{
    if(confirm('您确认要关闭本窗口吗?')){
      //关闭弹窗,并清空双向绑定的表单数据
      dialogVisible.value = false;
      saveUserForm.value = {};
    }
  }

  const editUser=(id)=>{
      //出弹窗 + 修改弹窗标题
  dialogVisible.value = true;
  dialogTitle.value = '编辑用户';
    //根据用户id查询当前用户的详细数据显示在弹窗表单中
    axios.get(BASE_URL+'/v1/user/select?id='+id).then((response)=>{
      if(response.data.code == 2000){
        //注意:后端返回的是List<UserVO>,所以查一条数据的话拿的是集合的第1个元素,data[0]等价list.get(0)
        saveUserForm.value = response.data.data[0];
        saveUserForm.value.empName=Object.keys(empLabelMap).find(key => empLabelMap[key] === saveUserForm.value.empName);
        saveUserForm.value = saveUserForm.value;
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }

  const deleteUser=(userId)=>{
    if(confirm('您确认要删除该用户吗?')){
      axios.post(BASE_URL+'/v1/user/delete/'+userId).then((response)=>{
        if(response.data.code==2000){
          ElMessage.success('删除成功!');
          loadUser();
        }else{
          ElMessage.error(response.data.msg);
        }
      })
    }
  }
</script>

<style scoped>

</style>